//
//  ComboBox.m
//  YYZB
//
//  Created by 顾悦 on 6/30/15.
//  
//

#import "ComboBox.h"

static const CGFloat tableViewCellHeight = 30.0f;

typedef void (^CompletionBlock)(NSString *selectedCode, NSString *selectedTitle);

@interface ComboBox () <UITableViewDataSource, UITableViewDelegate>

@property (copy, nonatomic) CompletionBlock completion;

@property (strong, nonatomic) UITableView *tableView;
@property (copy, nonatomic) NSString *codeFieldName;
@property (copy, nonatomic) NSString *titleFieldName;

@end

@implementation ComboBox

+ (instancetype)comboBoxWithDataSource:(NSArray *)dataSource code:(NSString *)code title:(NSString *)title frame:(CGRect)frame completion:(void (^)(NSString *selectedCode, NSString *selectedTitle))completion {
    ComboBox *comboBox = [[self alloc] initWithFrame:frame];
    comboBox.dataSource = dataSource;
    comboBox.codeFieldName = code;
    comboBox.titleFieldName = title;
    comboBox.completion = completion;
    
    return comboBox;
}

+ (instancetype)comboBoxWithDataSource:(NSArray *)dataSource
                                 frame:(CGRect)frame
                            completion:(void (^)(NSString *selectedCode, NSString *selectedTitle))completion {
    return [self comboBoxWithDataSource:dataSource code:nil title:nil frame:frame completion:completion];
}

- (void)setDropped:(BOOL)dropped {
    if (_dropped == dropped) {
        return;
    }
    
    _dropped = dropped;
    [self toggleDroppedStatus:dropped];
}

- (void)toggleDroppedStatus:(BOOL)dropped {
    if (dropped) {
        self.tableView.hidden = NO;
        [self.tableView.superview bringSubviewToFront:self.tableView];
    } else {
        self.tableView.hidden = YES;
    }
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setBackgroundImage:[[UIImage imageNamed:@"input_box.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 4, 4, 4) resizingMode:UIImageResizingModeStretch] forState:UIControlStateNormal];
        //    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, rect.size.width-20, 0, 0)];
        [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [self setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 20)];
        self.titleLabel.font = [UIFont systemFontOfSize:10.1];
        self.titleLabel.numberOfLines = 2;
        self.adjustsImageWhenHighlighted = NO;
        
        //12*7
        UIImageView *detail = [[UIImageView alloc] initWithFrame:CGRectMake(frame.size.width-20, (frame.size.height-7)/2, 12, 7)];
        detail.image = [UIImage imageNamed:@"detail_down.png"];
        detail.tag = 10;
        detail.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
        [self addSubview:detail];
    }
    
    return self;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = UITableView.new;
        _tableView.frame = CGRectMake(CGRectGetMinX(self.frame), CGRectGetMaxY(self.frame), CGRectGetWidth(self.frame), tableViewCellHeight * (self.dataSource.count > 3 ? 3 : self.dataSource.count));
        _tableView.dataSource = self;
        _tableView.delegate = self;
        if (self.superview) {
            [self.superview addSubview:_tableView];
        }
    }
    
    return _tableView;
}

- (void)setDataSource:(NSArray *)dataSource {
    if (self.dataSource == dataSource) {
        return;
    }
    _dataSource = dataSource;
    [_tableView reloadData];
}

- (NSString *)codeFieldName {
    if (_codeFieldName.length) {
        return _codeFieldName;
    }
    
    return [defaultCodeFieldName copy];
}

- (NSString *)titleFieldName {
    if (_titleFieldName.length) {
        return _titleFieldName;
    }
    
    return [defaultTitleFieldName copy];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:13.0];
        cell.backgroundColor = [UIColor lightGrayColor];
    }
    NSString *title = self.titleFieldName ?: defaultTitleFieldName;
    cell.textLabel.text = self.dataSource[indexPath.row][title];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.completion) {
        NSDictionary *selectedPair = self.dataSource[indexPath.row];
        self.completion(selectedPair[self.codeFieldName], selectedPair[self.titleFieldName]);
    }
    self.dropped = YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return tableViewCellHeight;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
